package work.chenxr.redis.sender;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import work.chenxr.redis.config.RedisListenerConfig;

import java.util.UUID;

/**
 * @Author Chenxr
 * @Date 2023/09/11
 * @Description Redis消息发送器
 */
@Component
@EnableScheduling
public class RedisMessageSender {
    private final StringRedisTemplate stringRedisTemplate;

    public RedisMessageSender(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 直接发送
     *
     * @param message 消息
     */
    public void sendMessage(String message) {
        stringRedisTemplate.convertAndSend(RedisListenerConfig.LISTENER_KEY, message);
    }

    /**
     * 间隔5s 通过StringRedisTemplate对象向消息队列 TEST 频道发布消息
     */
    @Scheduled(fixedRate = 5000)
    public void sendTimingMessage() {
        stringRedisTemplate.convertAndSend(RedisListenerConfig.LISTENER_TIMING_KEY, UUID.randomUUID().toString());
    }
}
